
//拼团活动
package shopping

import (
    "time"
	"strconv"
	"dhfshop/models"
	"dhfshop/models/consts"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

// 拼团规则数据
type Pintuan struct {
    PintuanId       int64     `orm:"column(pintuan_id);pk;auto" json:"pintuan_id" form:"pintuan_id"`              //自增ID
    PartnerId       int64       `orm:"column(partner_id)" json:"partner_id" form:"partner_id"`                      //商家ID
    StoreId         int64       `orm:"column(store_id)" json:"store_id" form:"store_id"`                            //门店id
	Name            string    `orm:"column(name)" json:"name" form:"name"`                                        //活动名称
	StartTime       time.Time `orm:"column(start_time);type(datetime);null" json:"-" form:"-"`                    //开始时间
	EndTime         time.Time `orm:"column(end_time);type(datetime);null" json:"-" form:"-"`                      //结束时间
	NeedCustomerNum int       `orm:"column(need_customer_num)" json:"need_customer_num" form:"need_customer_num"` //需要几个人
	ItemId          int64     `orm:"column(item_id);index" json:"-" form:"-"`  //商品ID
	ItemIdStr       string    `orm:"-" json:"item_id" form:"item_id"`
	SkuId           int64     `orm:"column(sku_id)" json:"-" form:"-"`       //规格ID
    SkuIdStr        string    `orm:"-" json:"sku_id" form:"sku_id"`
 OriginalPrice float32 `orm:"column(original_price);digits(12);decimals(2)" json:"original_price" form:"original_price"` //原价
	PinPrice        float32   `orm:"column(pin_price);digits(12);decimals(2)" json:"pin_price" form:"pin_price"` //拼团价
	CreatedTime     time.Time `orm:"auto_now_add;column(created_time);type(datetime)" json:"-" form:"-"`         //创建时间
    UpdatedTime     time.Time `orm:"auto_now;column(updated_time);type(datetime)" json:"-" form:"-"`             //更新时间
	ExpirationHour  float32   `orm:"column(expiration_hour)" json:"expiration_hour" form:"expiration_hour"`      //过期小时
	//非数据库字段
	StartTimeStr     string    `orm:"-" json:"start_time" form:"start_time"`                      //输入输出
	EndTimeStr       string    `orm:"-" json:"end_time" form:"end_time"`                          //输入输出
	
}
	
//顾客发起团购的数据
type PintuanActivity struct {
    PintuanActivityId int64      `orm:"column(pintuan_activity_id);pk;auto" json:"pintuan_activity_id" form:"-"`
	PartnerId          int64       `orm:"column(partner_id)" json:"partner_id" form:"-"`                               //商家ID
	StoreId            int64       `orm:"column(store_id)" json:"store_id" form:"store_id"`                            //门店id
	MemberId           int64     `orm:"column(member_id)" json:"member_id" form:"-"`                                 //团主id
	PintuanId          int64     `orm:"column(pintuan_id)" json:"pintuan_id" form:"pintuan_id"`                      //活动id
	NeedCustomerNum    int       `orm:"column(need_customer_num)" json:"need_customer_num" form:"-"`                 //需要几个人
	CurrentCustomerNum int       `orm:"column(current_customer_num)" json:"current_customer_num" form:"-"`           //当前几个人
	ItemId             int64     `orm:"column(item_id)" json:"item_id" form:"item_id"`                               //商品ID
	SkuId              int64     `orm:"column(sku_id)" json:"sku_id" form:"sku_id"`                                  //规格ID
	OriginalPrice      float32   `orm:"column(original_price);digits(12);decimals(2)" json:"original_price" form:"original_price"` //原价
	PinPrice           float32   `orm:"column(pin_price);digits(12);decimals(2)" json:"pin_price" form:"pin_price"` //拼团价
	StartTime          time.Time `orm:"column(start_time);type(datetime);null" json:"-" form:"-"`                   //活动开始时间
	EndTime            time.Time `orm:"column(end_time);type(datetime);null" json:"-" form:"-"`                     //活动结束时间
	CreatedTime        time.Time `orm:"auto_now_add;column(created_time);type(datetime)" json:"-" form:"-"`         //创建时间  
	ExpirationTime     time.Time `orm:"column(expiration_time);type(datetime)" json:"-" form:"-"`                   //实例过期时间  
}

//顾客参团的数据
type PintuanDetail struct {
    PintuanDetailId   int64     `orm:"column(pintuan_detail_id);pk;auto" json:"pintuan_detail_id" form:"-"`
	PartnerId         int64       `orm:"column(partner_id)" json:"partner_id" form:"partner_id"`             //商家ID
	PintuanActivityId int64     `orm:"column(pintuan_activity_id)" json:"pintuan_activity_id" form:"-"`
	MemberId          int64     `orm:"column(member_id)" json:"member_id" form:"-"`                        //顾客id
	OrderId           int64     `orm:"column(order_id)" json:"order_id" form:"order_id"`                   //订单id
	ItemId            int64     `orm:"column(item_id)" json:"item_id" form:"item_id"`                      //商品ID
	SkuId             int64     `orm:"column(sku_id)" json:"sku_id" form:"sku_id"`                         //规格ID
	CreatedTime       time.Time `orm:"auto_now_add;column(created_time);type(datetime)" json:"-" form:"-"` //入团时间  
	IsTuanzhang       bool      `orm:"column(is_tuanzhang)" json:"is_tuanzhang" form:"-"`                  //是否团长
}

func init() {
    orm.RegisterModel(new(Pintuan),new(PintuanActivity),new(PintuanDetail))   
}

func GetPintuanById(id int64) (v *Pintuan, err error) {
	o := models.GetDefaultDB()
	v = &Pintuan{PintuanId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func AddPintuanActivity(m *PintuanActivity) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetPintuanActivityById(id int64) (v *PintuanActivity, err error) {
	o := models.GetDefaultDB()
	v = &PintuanActivity{PintuanActivityId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func UpdatePintuanActivityById(m *PintuanActivity, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := PintuanActivity{PintuanActivityId: m.PintuanActivityId}
	if err = o.Read(&v); err != nil {
		return err
	}else{
	    if _, err = o.Update(m, k...); err != nil {
		   return err
		}
	}
	return nil
}

func AddPintuanDetail(m *PintuanDetail) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetPintuanDetailById(id int64) (v *PintuanDetail, err error) {
	o := models.GetDefaultDB()
	v = &PintuanDetail{PintuanDetailId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetPintuanDetailCountByActId(activityId int64) (cnt int64, err error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(PintuanDetail))
	qs = qs.Filter("pintuan_activity_id", activityId)
	if cnt, err = qs.Count(); err == nil {
	    return cnt, nil
	}
	return 0, err
}

func GetPintuanDetailsByActId(activityId int64) ([]*PintuanDetail, error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(PintuanDetail))
	qs = qs.Filter("pintuan_activity_id", activityId)
	var lists []*PintuanDetail
	_, err := qs.All(&lists)
	if err == nil {
		return lists, nil
	}
	return nil, err
}

//h, _:= time.ParseDuration("1m") 
//h, _:= time.ParseDuration("-1h")   
//sourceAt.Add(24*h)
func GetExpiringActivitys(sourceAt time.Time, limit, offset int)([]*PintuanActivity, error) {
	h, _:= time.ParseDuration("-1m")
	dstAt := sourceAt.Add(30*h)
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(PintuanActivity))
	qs = qs.Filter("expiration_time__gte", dstAt)
	var lists []*PintuanActivity
	_, err := qs.Limit(limit, offset).All(&lists)
	if err == nil {
		return lists, nil
	}
	return nil, err
}

func GetTimeValidPinTuans(itemId int64) (pinTuans []*Pintuan, err error) {
	curUtcTime := time.Now().UTC()
	pinTuans = []*Pintuan{}
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Pintuan)).Filter("item_id", itemId)
	qs = qs.Filter("start_time__lt", curUtcTime)
	qs = qs.Filter("end_time__gt", curUtcTime)
	if _, err = qs.All(&pinTuans); err == nil {
	    for _, tuan := range pinTuans {
			tuan.StartTimeStr = tuan.StartTime.Format(consts.DATETIME_FORMAT)
			tuan.EndTimeStr = tuan.EndTime.Format(consts.DATETIME_FORMAT)
			tuan.ItemIdStr = strconv.FormatInt(tuan.ItemId, 10)
			tuan.SkuIdStr = strconv.FormatInt(tuan.SkuId, 10)
		}
	}
	return
}
